package com.chuck.learning.线程间通讯;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SafeQueue {
    private Object[] element;

    public SafeQueue(int capacity) {
        this.element = new Object[capacity];
    }

    private int addIndex;

    private int removeIndex;

    private int currentSize;

    Lock lock = new ReentrantLock();

    Condition full = lock.newCondition();
    Condition empty = lock.newCondition();

    public void add(Object object) throws InterruptedException {
        lock.lock();
        if (currentSize == element.length) {
            System.out.println("满了满了");
            full.await();
        }
        if (addIndex  == element.length) {
            addIndex = 0;
        }
        element[addIndex++] = object;
        currentSize++;
        empty.signal();

        lock.unlock();
    }

    public Object remove() throws InterruptedException {
        try {
            lock.lock();
            if (currentSize == 0) {
                System.out.println("队列已经空了");
                empty.await();
            }
            if (removeIndex+1==element.length) {
                removeIndex = 0;
            }
            Object o = element[removeIndex];

            element[removeIndex++] = null;
            currentSize--;

            full.signal();
            return o;

        } finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        SafeQueue safeQueue= new SafeQueue(10);
        new Thread(()->{
            int i=0;
            while (true){
                try {
                    Thread.sleep(100);
                    safeQueue.add(++i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();


        new Thread(()->{
            while (true){
                try {
                    Thread.sleep(5000);
                    System.out.println(safeQueue.remove());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }
}
